/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MonetyWnd.java
 *
 * Created on 2011-10-30, 10:56:40
 */
package monety;

import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

/**
 *
 * @author Jedrek
 */
public class MonetyWnd extends javax.swing.JFrame {

    Monety monety;
    
    /** Creates new form MonetyWnd */
    public MonetyWnd(Monety monety) {
        this.monety = monety;
        
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane1 = new javax.swing.JScrollPane();
        coinsTable = new javax.swing.JTable();
        tfName = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tfYear = new javax.swing.JTextField();
        bAdd = new javax.swing.JButton();
        bUpdate = new javax.swing.JButton();
        bFind = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        findTable = new javax.swing.JTable();
        bDelete = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        mFile = new javax.swing.JMenu();
        mSave = new javax.swing.JMenuItem();
        mLoad = new javax.swing.JMenuItem();
        mCoins = new javax.swing.JMenu();
        mSortByName = new javax.swing.JMenuItem();
        mSortByYear = new javax.swing.JMenuItem();
        mSortByCount = new javax.swing.JMenuItem();

        jButton1.setText("jButton1");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        coinsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "Year", "Count"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        coinsTable.setColumnSelectionAllowed(true);
        coinsTable.setGridColor(new java.awt.Color(204, 204, 204));
        coinsTable.setShowVerticalLines(false);
        coinsTable.getTableHeader().setReorderingAllowed(false);
        coinsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                coinsTableMouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                coinsTableMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(coinsTable);
        coinsTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        coinsTable.getColumnModel().getColumn(1).setMinWidth(10);
        coinsTable.getColumnModel().getColumn(1).setPreferredWidth(45);
        coinsTable.getColumnModel().getColumn(1).setMaxWidth(60);
        coinsTable.getColumnModel().getColumn(2).setMinWidth(10);
        coinsTable.getColumnModel().getColumn(2).setPreferredWidth(45);
        coinsTable.getColumnModel().getColumn(2).setMaxWidth(60);

        jLabel1.setText("Name:");

        jLabel2.setText("Year:");

        bAdd.setText("Add");
        bAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAddActionPerformed(evt);
            }
        });

        bUpdate.setText("Update");

        bFind.setText("Find");
        bFind.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bFindActionPerformed(evt);
            }
        });

        findTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "Year", "Count", "Correlation"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        findTable.setGridColor(new java.awt.Color(204, 204, 204));
        findTable.setShowVerticalLines(false);
        findTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                findTableMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(findTable);
        findTable.getColumnModel().getColumn(1).setPreferredWidth(25);
        findTable.getColumnModel().getColumn(2).setPreferredWidth(25);
        findTable.getColumnModel().getColumn(3).setPreferredWidth(25);

        bDelete.setText("Delete");
        bDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bDeleteActionPerformed(evt);
            }
        });

        mFile.setText("File");

        mSave.setText("Save");
        mSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mSaveActionPerformed(evt);
            }
        });
        mFile.add(mSave);

        mLoad.setText("Load");
        mLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mLoadActionPerformed(evt);
            }
        });
        mFile.add(mLoad);

        jMenuBar1.add(mFile);

        mCoins.setText("Coins");

        mSortByName.setText("Sort by name");
        mSortByName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mSortByNameActionPerformed(evt);
            }
        });
        mCoins.add(mSortByName);

        mSortByYear.setText("Sort by year");
        mSortByYear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mSortByYearActionPerformed(evt);
            }
        });
        mCoins.add(mSortByYear);

        mSortByCount.setText("Sort by count");
        mSortByCount.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mSortByCountActionPerformed(evt);
            }
        });
        mCoins.add(mSortByCount);

        jMenuBar1.add(mCoins);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 346, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(bFind, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(bAdd, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bDelete))
                    .addComponent(tfYear, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tfName, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tfName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tfYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bAdd)
                    .addComponent(bDelete)
                    .addComponent(bUpdate))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bFind)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAddActionPerformed
        Coin coin;
        String name;
        int year;
        
        name = tfName.getText();
        if(name.length() == 0){
            JOptionPane.showMessageDialog(this, "Invalid name", "Invalid parameter", JOptionPane.ERROR_MESSAGE);
            return;
        }
        try{
            year = Integer.parseInt(tfYear.getText());
        } catch (Exception e){
            JOptionPane.showMessageDialog(this, "Invalid year", "Invalid parameter", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        monety.addCoin(name, year);
    }//GEN-LAST:event_bAddActionPerformed

    private void mSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mSaveActionPerformed
        JFileChooser fc = new JFileChooser();
        
        if(fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION){
            monety.saveList(fc.getSelectedFile().getPath());
        }
    }//GEN-LAST:event_mSaveActionPerformed

    private void mLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mLoadActionPerformed
        JFileChooser fc = new JFileChooser();
        
        if(fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){
            monety.loadList(fc.getSelectedFile().getPath());
        }
    }//GEN-LAST:event_mLoadActionPerformed

    private void mSortByNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mSortByNameActionPerformed
        monety.sortByName();
    }//GEN-LAST:event_mSortByNameActionPerformed

    private void mSortByYearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mSortByYearActionPerformed
        monety.sortByYear();
    }//GEN-LAST:event_mSortByYearActionPerformed

    private void mSortByCountActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mSortByCountActionPerformed
        monety.sortByCount();
    }//GEN-LAST:event_mSortByCountActionPerformed

    private void coinsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_coinsTableMouseClicked
        int row = coinsTable.getSelectedRow();
        if(row >= 0 && evt.getClickCount()==2){
            Coin coin = (Coin)coinsTable.getModel().getValueAt(row, 0);
            if(coin != null){
                tfName.setText(coin.getName());
                tfYear.setText(coin.year + "");
            }
        }
    }//GEN-LAST:event_coinsTableMouseClicked

    private void coinsTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_coinsTableMouseReleased
        
    }//GEN-LAST:event_coinsTableMouseReleased

    private void bFindActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bFindActionPerformed
        Coin coin = null;
        String name;
        int year;
        
        name = tfName.getText();
        if(name.length() == 0){
            JOptionPane.showMessageDialog(this, "Invalid name", "Invalid parameter", JOptionPane.ERROR_MESSAGE);
            return;
        }
        try{
            year = Integer.parseInt(tfYear.getText());
        } catch (Exception e){
            JOptionPane.showMessageDialog(this, "Invalid year", "Invalid parameter", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        coin = new Coin(name, year);
        ArrayList<Float> cor = new ArrayList<Float>();
        ArrayList<Coin> result = monety.find(coin, cor);
        
        Object [][] content = new Object[result.size()][4];
        Object [] columns = {"Name", "Year", "Count", "Correlation"};
        
        for( int i=0; i<result.size(); i++ ){
            coin = result.get(i);
            content[i][0] = coin;
            content[i][1] = coin.year + "";
            content[i][2] = coin.getCount() + "";
            content[i][3] = (int)(100*cor.get(i).floatValue()) + "%";
        }
        
        TableModel model = new MyTableModel(content, columns);
        
        findTable.setModel(model);
        TableColumnModel tableColumnModel = findTable.getColumnModel();
        tableColumnModel.getColumn(1).setMinWidth(10);
        tableColumnModel.getColumn(1).setMaxWidth(60);
        tableColumnModel.getColumn(1).setPreferredWidth(45);
        tableColumnModel.getColumn(2).setMinWidth(10);
        tableColumnModel.getColumn(2).setMaxWidth(50);
        tableColumnModel.getColumn(2).setPreferredWidth(35);
        tableColumnModel.getColumn(3).setMinWidth(10);
        tableColumnModel.getColumn(3).setMaxWidth(60);
        tableColumnModel.getColumn(3).setPreferredWidth(45);
    }//GEN-LAST:event_bFindActionPerformed

    private void bDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bDeleteActionPerformed
        Coin coin = null;
        String name;
        int year;
        
        name = tfName.getText();
        if(name.length() == 0){
            JOptionPane.showMessageDialog(this, "Invalid name", "Invalid parameter", JOptionPane.ERROR_MESSAGE);
            return;
        }
        try{
            year = Integer.parseInt(tfYear.getText());
        } catch (Exception e){
            JOptionPane.showMessageDialog(this, "Invalid year", "Invalid parameter", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        coin = new Coin(name, year);
        if(monety.deleteCoin(coin))
            JOptionPane.showMessageDialog(this, "Coin removed succesfully!", "Success!", JOptionPane.INFORMATION_MESSAGE);
        else
            JOptionPane.showMessageDialog(this, "Couldn remove the coin. Coin not found!", "Fail!", JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_bDeleteActionPerformed

    private void findTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_findTableMouseClicked
        int row = findTable.getSelectedRow();
        if(row >= 0 && evt.getClickCount()==2){
            Coin coin = (Coin)findTable.getModel().getValueAt(row, 0);
            if(coin != null){
                tfName.setText(coin.getName());
                tfYear.setText(coin.year + "");
            }
        }
    }//GEN-LAST:event_findTableMouseClicked

    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                new MonetyWnd().setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bAdd;
    private javax.swing.JButton bDelete;
    private javax.swing.JButton bFind;
    private javax.swing.JButton bUpdate;
    private javax.swing.JTable coinsTable;
    private javax.swing.JTable findTable;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JMenu mCoins;
    private javax.swing.JMenu mFile;
    private javax.swing.JMenuItem mLoad;
    private javax.swing.JMenuItem mSave;
    private javax.swing.JMenuItem mSortByCount;
    private javax.swing.JMenuItem mSortByName;
    private javax.swing.JMenuItem mSortByYear;
    private javax.swing.JTextField tfName;
    private javax.swing.JTextField tfYear;
    // End of variables declaration//GEN-END:variables


    public void showCoins(ArrayList<Coin> list){   
        Object [][] content = new Object[list.size()][3];
        Object [] columns = {"Name", "Year", "Count"};
        Coin coin;
        for( int i=0; i<list.size(); i++ ){
            coin = list.get(i);
            content[i][0] = coin;
            content[i][1] = coin.year + "";
            content[i][2] = coin.getCount() + "";
        }
        
        TableModel model = new MyTableModel(content, columns);
        
        coinsTable.setModel(model);
        TableColumnModel tableColumnModel = coinsTable.getColumnModel();
        tableColumnModel.getColumn(1).setMinWidth(10);
        tableColumnModel.getColumn(1).setMaxWidth(60);
        tableColumnModel.getColumn(1).setPreferredWidth(45);
        tableColumnModel.getColumn(2).setMinWidth(10);
        tableColumnModel.getColumn(2).setMaxWidth(50);
        tableColumnModel.getColumn(2).setPreferredWidth(35);
    }
}

class MyTableModel extends DefaultTableModel{
    
    public MyTableModel(Object [][] content, Object [] columns){
        super(content, columns);

    }
    
    @Override
    public boolean isCellEditable(int row, int column) {
       //all cells false
       return false;
    }
}